import akshare as ak

from datetime import datetime
from easymoney.framework.mysql.core.db_factory import MainForceControlEntity, db


# 拉取每天最新的数据
def fetch_latest_daily_data(code):
    # 主力控盘
    df = ak.stock_comment_detail_zlkp_jgcyd_em(symbol=code)
    max_date_index = df['date'].idxmax()
    # 获取昨天最新的一条数据
    row_with_max_age = df.loc[max_date_index]
    obj = query_by_code_date(code, row_with_max_age['date'])
    if obj is not None:
        return obj
    else:
        entity = MainForceControlEntity(
            stock_code=code,
            date=row_with_max_age['date'],
            value=row_with_max_age['value']
        )
        # 保存到数据库
        with db:
            # 在这里执行数据库操作
            try:
                entity.save()
            except Exception as e:
                print(e)


def fetch_all_data(code):
    mf = query_by_code(code)
    if mf is None:
        # 主力控盘
        df = ak.stock_comment_detail_zlkp_jgcyd_em(symbol=code)
        for index, row in df.iterrows():
            entity = MainForceControlEntity(
                stock_code=code,
                date=row['date'],
                value=row['value']
            )
            # 保存到数据库
            with db:
                # 在这里执行数据库操作
                entity.save()


def query_by_code(code):
    return MainForceControlEntity.get_or_none(MainForceControlEntity.stock_code == code)


def query_by_code_date(code, date):
    return MainForceControlEntity.get_or_none(
        MainForceControlEntity.stock_code == code, MainForceControlEntity.date == date)

